import { useState, useEffect, useRef } from 'react'

const Clear = () => {
  const [count, setCount] = useState(0)
  // 定时器ID
  // let timerId = -1
  let timerId = useRef(0)

  // 组价挂载了
  useEffect(() => {
    timerId.current = setInterval(() => {
      console.log('interval')
    }, 1000)
    // 这个ID是随机的,只是为了区分不同的定时器
    console.log('第一次存定时器ID：', timerId.current)
  }, [])

  // 清除定时器=》问题：点击修改状态之后，定时器清除失效？
  const clear = () => {
    console.log('改了状态之后的定时器ID：', timerId.current)

    clearInterval(timerId.current)
  }

  const handleClick = () => {
    setCount(count + 1)
  }

  return (
    <div>
      <h1>计数器：{count}</h1>
      <button onClick={handleClick}>+1</button>
      <button onClick={clear}>清理定时器</button>
    </div>
  )
}

export default Clear
